<template>
  <div class="main main-sscontent">
    <div class="part">
      <div class="p-title">
        <div class="title">
          <span>内容管理</span>
          <!-- <MyToolTip
            content="指标定义：截止到筛选日期，所有获得过大病保障的绝对总人数"
          /> -->
        </div>
        <div class="search-warp">
          <el-input
            v-model="searchContent"
            placeholder="请输入关键词进行搜索"
            @change="searchDrugs"
          >
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>
      </div>
      <div class="p-cont">
        <div class="opr">
          <div class="opr-left">
            <el-button type="primary" @click="createNewDist"
              >新建内容</el-button
            >
          </div>
        </div>
        <div class="table-wrap">
          <el-table :data="distList" style="width: 100%" stripe>
            <el-table-column prop="title" label="标题" width="220" />
            <el-table-column label="描述">
              <template #default="scope">
                <!-- <el-tooltip
                  placement="bottom"
                  effect="light"
                  raw-content
                  :content="scope.row.description"
                  popper-class="tooltip-popper"
                >
                </el-tooltip> -->
                {{ formatHtmlDes(scope.row.description, 20) }}
                <!-- <div v-html="scope.row.description" /> -->
              </template>
            </el-table-column>
            <el-table-column label="频道" width="120">
              <template #default="scope">
                {{ scope.row.type === 1 ? "系统消息" : "宣传方案" }}
              </template>
            </el-table-column>

            <el-table-column prop="createDate" label="更新时间" width="200" />
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="checkDist(scope.row)"
                  >查看</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="changDist(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="deleteContent(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="del-btn">
          <!-- <div class="del-left">
            <el-button type="primary" @click="plDeleteDrugs"
              >批量删除</el-button
            >
          </div> -->
          <div class="del-right">
            <myPagination
              :total="listNum || 0"
              @currentChange="currentChange"
              ref="myPaginationRef"
            />
          </div>
        </div>
        <!-- <div class="page">
          <div class="page-left">共{{ listNum }}条数据</div>
        </div> -->
      </div>

      <el-dialog v-model="dialogVisible" title="新建/编辑内容">
        <div class="dialog-adddrug">
          <el-form
            :model="form"
            label-width="120px"
            ref="ruleFormRef"
            :rules="rules"
          >
            <el-form-item label="频道" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择频道"
                :disabled="editType === 'check' ? true : false"
              >
                <el-option
                  v-for="item in dataTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入标题"
                :disabled="editType === 'check' ? true : false"
              />
            </el-form-item>
            <el-form-item label="内容描述" prop="description">
              <!-- <el-input
                v-model="form.description"
                placeholder="请输入内容"
                type="textarea"
                :disabled="editType === 'check' ? true : false"
              /> -->
              <div
                class="edit-cont"
                v-show="editType === 'check'"
                v-html="form.description"
              />
              <div
                class="editor-wrap"
                v-show="editType === 'new' || editType === 'edit'"
              >
                <ckeditor
                  :editor="editor"
                  v-model="form.description"
                  :config="editorConfig"
                />
              </div>
            </el-form-item>
            <el-form-item label="附件">
              <el-upload
                ref="uploadRef"
                v-model:file-list="uploadFileList"
                class="upload-demo"
                :action="actionUrl"
                :headers="uploadHeaders"
                :show-file-list="true"
                :on-error="uploadError"
                :on-progress="uploadProgress"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
                :disabled="editType === 'check' ? true : false"
              >
                <el-button
                  type="primary"
                  :disabled="editType === 'check' ? true : false"
                  :loading="uploadLoading"
                  >上传附件</el-button
                >
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button @click="resetSubmit" v-if="editType === 'new'"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click="submitForm"
                :disabled="editType === 'check' ? true : false"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import myPagination from "@/components/myPagination.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import { formatHtmlDes } from "@/utils/tools";

import {
  getContentManagements,
  getContentManagementDetail,
  createContentMangements,
  deleteContentManagements
} from "@/api/system";
import { getToken, formatToken } from "@/utils/auth";
import { component as ckeditor } from "@ckeditor/ckeditor5-vue";
import { whReqBaseUrl as VITE_REQUEST_BASE_SAAS_API } from "@/api/common";

const editor = ClassicEditor;

// const plugins = ClassicEditor.builtinPlugins.map(plugin => plugin.pluginName);
// console.log("plugins:", plugins);

const editorConfig = {
  toolbar: [
    "heading",
    "|",
    "bold",
    "italic",
    "link",
    "bulletedList",
    "numberedList",
    "|",
    "blockQuote",
    "undo",
    "redo"
  ],
  language: "zh-cn",
  link: {
    decorators: {
      isExternal: {
        mode: "manual",
        label: "是否是外链",
        attributes: {
          target: "_blank",
          rel: "noopener noreferrer"
        }
      },
      isDownloadable: {
        mode: "manual",
        label: "是否是下载"
      }
    }
  }
};

const uploadRef = ref();
const actionUrl = ref(
  `${VITE_REQUEST_BASE_SAAS_API}/contentManagements/uploadFile`
);
const uploadLoading = ref(false);

// 请求头部
const data = getToken();
const uploadHeaders = {
  Authorization: formatToken(data.accessToken)
};

const userStore = useUserStoreHook();
const listNum = ref(0);
const myPaginationRef = ref();
const distList = ref([]);
const userId = useUserStoreHook().userInfo.user;
const dialogVisible = ref(false);
const ruleFormRef = ref();
const form = ref({
  id: "",
  type: 1,
  title: "",
  description: "",
  files: []
});
const searchContent = ref();

const editType = ref<"check" | "new" | "edit">("new");
const dataTypeOptions = [
  {
    value: 1,
    label: "系统消息"
  },
  {
    value: 2,
    label: "宣传方案"
  }
];
const uploadFileList = ref([]);

const rules: any = reactive({
  type: [
    {
      required: true,
      type: "number",
      message: "请选择消息频道",
      trigger: "blur"
    }
  ],
  title: [
    { required: true, message: "标题不能为空，且不大于20个字符", max: 20 }
  ],
  description: [{ required: true, message: "内容不能为空" }]
});

function uploadError(error, uploadFile) {
  console.log("error:", error);
  console.log("uploadFile:", uploadFile);
  ElMessage({
    type: "error",
    message: "上传报错,请重新上传:" + JSON.stringify(error)
  });
}
function uploadProgress(evt, uploadFile) {
  console.log("  uploadProgress evt:", evt, " ,uploadFile:", uploadFile);
}

function beforeUpload() {
  uploadLoading.value = true;
}

function uploadSuccess() {
  uploadLoading.value = false;
}

function searchDrugs() {
  myPaginationRef.value.currentPage = 1;
  getContentApi();
}
function currentChange() {
  getContentApi();
}

async function checkDist(data) {
  dialogVisible.value = true;
  editType.value = "check";
  const res = await getContentManagementDetail(data.id);
  uploadFileList.value = res.files.map(item => {
    return {
      name: item.title,
      url: item.url
    };
  });
  form.value = res;
}
async function changDist(data) {
  dialogVisible.value = true;
  editType.value = "edit";
  // 获取详情
  const res = await getContentManagementDetail(data.id);
  uploadFileList.value = res.files.map(item => {
    return {
      name: item.title,
      url: item.url
    };
  });
  form.value = res;
}

function createNewDist() {
  editType.value = "new";
  dialogVisible.value = true;
  resetSubmit();
  ruleFormRef.value?.clearValidate();
}

async function getContentApi() {
  const queryObj = {
    skip:
      (myPaginationRef.value.currentPage - 1) *
      myPaginationRef.value.curPageSize,
    limit: myPaginationRef.value.curPageSize
  } as any;
  if (searchContent.value) {
    queryObj.search = searchContent.value;
  }
  const listRes = await getContentManagements(queryObj);
  distList.value = listRes.list;
  if (myPaginationRef.value.currentPage === 1) {
    listNum.value = listRes.total;
  }
}

function deleteContent(dist) {
  ElMessageBox.alert(`确定要删除"${dist.title}"吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(async () => {
    await deleteContentManagements(dist.id, { userId });
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    await getContentApi();
  });
  return;
}

function formatDist(areaObj) {
  let temp = areaObj.provinceName;
  if (areaObj.cityName) {
    temp += "-" + areaObj.cityName;
  }

  if (areaObj.areaName) {
    temp += "-" + areaObj.areaName;
  }
  return temp;
}

function submitForm() {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const tempForm = Object.assign({}, form.value);
        console.log("uploadFileList:", uploadFileList);
        // 对files进行处理
        tempForm.files = uploadFileList.value.map(item => {
          //  带response为上传的文件
          if (item.response) {
            const fileRes = item.response.data;
            return {
              title: fileRes.fileName,
              url: fileRes.url
            };
          } else {
            return {
              title: item.name,
              url: item.url
            };
          }
        });
        if (tempForm.files.length > 0) {
          // 检查有没有空url的，有的话则提示用户重新上传
          const hasEmptyUrl = tempForm.files.find(item => {
            return !item.url;
          });
          if (hasEmptyUrl) {
            ElMessage({
              message: "附件上传失败,请重新上传",
              type: "error"
            });
            return;
          }
        }

        if (editType.value === "new") {
          delete tempForm.id;
        }
        const tip = editType.value === "new" ? "新增" : "编辑";
        try {
          const res = await createContentMangements({
            userId: userStore.userInfo.user,
            data: JSON.stringify(tempForm)
          });
          if (!res || res.code === 0) {
            ElMessage({
              message: tip + "成功",
              type: "success"
            });
            resetSubmit();
          }
          dialogVisible.value = false;
          getContentApi();
        } catch (error) {
          ElMessage({
            message: tip + "失败," + JSON.stringify(error),
            type: "error"
          });
        }
      }
    });
  }
}

function resetSubmit() {
  uploadFileList.value = [];
  form.value = {
    id: "",
    type: 1,
    title: "",
    description: "",
    files: [] //健康教育目标人数
  };
}

onMounted(async () => {
  await getContentApi();
});
</script>
<style scoped lang="scss">
::v-deep(.el-backtop) {
  display: none !important;
}

.main {
  .part {
    .p-title {
    }
  }
}

.search-warp {
  width: 300px;
}

.opr {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opr-right {
    width: 300px;
  }
}

.table-wrap {
  margin-top: 20px;

  .des-cont {
    height: 100px;
  }
}

.del-btn {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .page-left {
    color: #bbb;
  }
}

.dialog-adddrug {
  width: 600px;

  .dist-row {
    display: flex;
    align-items: center;

    .dist-btn {
      margin: 0px 10px 10px 0px;
    }
  }
}

.el-select {
  width: 100%;
}

.upload-demo {
  width: 300px;
}

::v-deep(.el-upload-list__item) {
  transition: none !important;
}

::v-deep(.el-form-item__label) {
  font-weight: bold;
}

::v-deep(.el-form-item__content) {
  .edit-cont {
    p {
      padding: 0px;
      margin: 0px;
    }
  }

  .editor-wrap {
    width: 100%;
  }
}
</style>
<style language="scss">
.ck-editor__main,
.ck-content {
  min-height: 120px !important;
}

.ck-balloon-panel {
  z-index: 10000 !important;
}
</style>
